<template>
  <div :id="chartId" style="width: 100%; height: 100%; padding: 10px"></div>
</template>

<script setup>
import echarts from "@/plugins/echarts.js";
import { v4 as uuidv4 } from "uuid";
import {
  reactive,
  onMounted,
  watch,
  onUnmounted,
  toRefs,
  markRaw,
  ref,
} from "vue";
const emits = defineEmits(["click"]);
const props = defineProps({
  options: {
    type: Object,
    default: () => {},
  },
  loop: {
    type: Boolean,
    default: false,
  },
});

const data = reactive({
  chartId: uuidv4(),
  chartInstance: null,
});
const { chartId, chartInstance } = toRefs(data);

onMounted(() => {
  chartInit();
});

function chartInit() {
  chartInstance.value = markRaw(
    echarts.init(document.getElementById(chartId.value))
  );
  chartInstance.value.setOption(props.options);
  chartInstance.value.on("click", (params) => {
    emits("click", params);
  });
  window.addEventListener("resize", resize);
}

function resize(options = {}) {
  if (chartInstance.value) {
    chartInstance.value.resize();
    chartInstance.value.setOption(options || props.options);
  }
}

watch(
  () => props.options,
  (nV) => {
    console.log("options", nV);

    resize(nV);
  },
  {
    immediate: true,
    deep: true,
  }
);

let currentIndex = ref(0);
let trendsTooltip = ref(null);
if (props.loop) {
  // 动态显示tootip
  // 当前高亮图形所在下标
  // 取消之前高亮的图形
  trendsTooltip = setInterval(function () {
    let dataLen = props.options.series[0].data.length;
    chartInstance.value.dispatchAction({
      type: "downplay",
      seriesIndex: 0,
      dataIndex: currentIndex.value,
    });
    // 当前高亮图形
    currentIndex.value = (currentIndex.value + 1) % dataLen;
    chartInstance.value.dispatchAction({
      type: "highlight",
      seriesIndex: 0,
      dataIndex: currentIndex.value,
    });
    // 显示 tooltip
    // tootip每隔三秒依次显示
    chartInstance.value.dispatchAction({
      type: "showTip", // 根据 tooltip 的配置项显示提示框。
      seriesIndex: 0,
      dataIndex: currentIndex.value,
    });
    if (currentIndex.value >= props.options.series[0].data.length) {
      currentIndex.value = 0;
    }
    console.log(21312321);
  }, 2000);
}

onUnmounted(() => {
  if (trendsTooltip.value) {
    clearInterval(trendsTooltip.value);
  }
  window.removeEventListener("resize", resize);
});
defineExpose({});
</script>
